package com.qianyu.project.web.controller.base;

import com.qianyu.project.core.context.user.FlowUserManager;
import com.qianyu.project.entity.SystemUser;
import com.qianyu.project.service.ISystemUserService;
import com.qianyu.project.utils.JwtUtils;
import com.qianyu.project.utils.Result;
import com.qianyu.project.utils.ResultTool;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;

/**
 * @author gs
 * @date create in 2020/12/23 15:59
 */
@RestController
public class LoginController {

    @Autowired
    private FlowUserManager flowUserManager;

    @PostMapping("/success")
    public Result success() {
        //获取认证对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //获取用户名和权限
        SystemUser systemUser = (SystemUser) authentication.getPrincipal();
        String username = systemUser.getUsername();
        Collection<GrantedAuthority> authorities = systemUser.getAuthorities();
        //生成token
        String token = JwtUtils.generateToken(username, StringUtils.collectionToCommaDelimitedString(authorities));
        //将用户信息存入流程用户提供者
        flowUserManager.pushSysUser(systemUser);
        flowUserManager.setSysUser(username);
        //获取角色
        List<String> roles = Lists.newArrayList();
        authorities.iterator().forEachRemaining(grantedAuthority -> {
            if(grantedAuthority.getAuthority().startsWith("ROLE_")){
                roles.add(grantedAuthority.getAuthority().replace("ROLE_", ""));
            }
        });
        //响应给浏览器
        return ResultTool.success("登陆成功", token).put("username", username).put("realName", systemUser.getUserRealname()).put("roles",StringUtils.collectionToCommaDelimitedString(roles));
    }

    @PostMapping("/error")
    public Result error() {
        //返回错误信息
        return ResultTool.failure("用户名或密码错误");
    }

    @RequestMapping("/exit")
    public Result logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = (String) authentication.getPrincipal();
        flowUserManager.removeSysUser(username);
        return ResultTool.success("注销成功！");
    }
}
